package com.laikan.reader.core.utils;

import android.content.Context;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.BaseListDataBean;
import com.laikan.reader.core.interfaces.ProDirectoryData;
import com.laikan.reader.database.Book;
import com.laikan.reader.database.DBBook;
import com.socks.library.KLog;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class BookNetUtils {

    private static final String TAG = "BookNetUtils";
    private static ArrayList<Book> books;

    static {
        books = new ArrayList<Book>();
    }

    /**
     * 获取单本书籍最新信息,
     * 判断是否有最新章节,
     * 有则更新目录,从新设置阅读页的目录数据
     *
     * @param mContext
     * @param bookid 书籍id
     * @param proData 判断是否有最新章节,和更新目录数据的回调函数
     */
    public static void getBookInfoAsync(final Context mContext, String bookid, ProDirectoryData proData) {
        final ProDirectoryData mproData = proData;
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("bookId", bookid);
        String url = APIProtocol.getRootURL2() + "bookshelf";
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                KLog.e(TAG, "getBookInfoAsync() json = " + httpResponse.responseContent);
                BaseDataBean<BaseListDataBean<Book>> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<BaseListDataBean<Book>>>() {
                }.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (result.getData() != null && result.getData().getBookList() != null) {
                        books = result.getData().getBookList();
                        if (books.size() > 0) {
                            mproData.proDirectoryData(books.get(0));
                        }
                    }
                }catch (JsonSyntaxException e) {
                    // 数据解析失败
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    KLog.e("网络不给力，请重试 BookNetUtils 68");
                    e.printStackTrace();
                    return;
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_get_bookshelf);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_get_bookshelf, map, null, null, requestListener);
    }

    /**
     * 同步本地书架中的书籍列表到网络
     *
     */
    public static void uploadBookshelfToServer() {
        List<Book> bookList = DBBook.getInstance().queryAllBook();
        if (bookList == null || bookList.size() <= 0) {
            return;
        }
        HashMap<String, String> map = new HashMap<String, String>();
        StringBuilder sb = new StringBuilder();
        map.put("sd", SPUtil.getString("token", ""));
        for (Book b : bookList) {
            sb.append(b.getId() + ":");
        }
        map.put("followBookId", sb.substring(0, sb.length() - 1));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                try {
                    JSONObject obj = new JSONObject(httpResponse.responseContent);
                    String result = obj.getString("result");
                    if (Constants.RESULT_OK.equals(result)) {
//                        ToastMgr.showShortToast(R.string.bookshelf_sync_success);
                    }
                }catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.bookshelf_sync_failed);
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL2() + "follow_book");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.getRootURL2() + "follow_book", map, null, null, requestListener);
    }
}
